﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Messaging;
using System.Threading.Tasks;
using System.Xml.Serialization;
using OrderReceiveService;
using OrdersDAL;
using OrdersDAL.EntityModel;
using Core;


namespace OrderReceiveService
{
    class Program
    {

        private static string _QueuePath;
        private static MessagingService _MessagingService;
        private static string _LoggedUser;
        private static bool _KeepRunning = true;
       
        /// <summary>
        /// Service Receieving new Orders And Process them
        /// </summary>
        /// <param name="args"></param>
        static void Main(string[] args)
        {
            _LoggedUser=Login();
            
            Console.ForegroundColor = ConsoleColor.Green;
 
            StartOrderAsyncReciever();
        }


        static void StartOrderAsyncReciever()
        {
            _QueuePath = Settings.Default.MSMQURL + string.Format("\\{0}", _LoggedUser);

            _MessagingService = new MessagingService(_QueuePath);

            var acceptCancelKey = Task.Factory.StartNew(
            () => AcceptCancelAsync());

            Console.WriteLine("Receiving Messagess Started....\r\nPress Esc to Cancel...");

            while (_KeepRunning)
            {
                var task = Task.Factory.StartNew(() => _MessagingService.Receive<Orders>());

                task.ContinueWith(
                    (t) =>
                    {
                        OnOrderReceiveCompleted
                            (t.Exception == null ? t.Result : null,
                            task.Id,
                            t.Exception);
                    });
            }
        }


        static void OnOrderReceiveCompleted(Orders order, int transid, Exception ex)
        {
            if (order != null)
            {
                    if (BL.ProcessOrder(order))
                    {
                        OnOrderProcessed(true, order.Id, transid, ex);
                    }

            }
        }

        static void OnOrderProcessed(bool result, int orderid, int transid, Exception ex)
        {
            if (result)
            {
                Console.WriteLine("Order {0} receieved and succesfully processed in TransactionId {1}", orderid, transid);
                var clients = _MessagingService.GetWinClientQueuePaths(Environment.MachineName);
                List<DemandCell> DemandCellList = BL.GetDemandCells();
                _MessagingService.Send<List<DemandCell>>(DemandCellList, clients, Settings.Default.MessageTTL);
            }
           
        }

        private static string Login()
        {
            Console.WriteLine("Please Enter User Name:");

            string UserName = string.Empty;

            bool ReadUserName = true;

            while (ReadUserName)
            {
                UserName = Console.ReadLine();

                if (string.IsNullOrEmpty(UserName))
                {
                    Console.WriteLine("User Name cannot be empty");
                }
                else
                {
                    ReadUserName = false;
                    Console.WriteLine("Logged as User {0}", UserName);
                }
            }
            return UserName;
        }

        private static void AcceptCancelAsync()
        {
            var key = Console.ReadKey(true);
            while (key.Key != ConsoleKey.Escape)
            {
                key = Console.ReadKey(true);
            }
            _KeepRunning = false;
            Console.WriteLine("Order Creation was cancelled");
        }
    }
}
